package com.loongtech.bi.action.biclient;

import com.loongtech.bi.action.BaseBiSearchAction;
import com.loongtech.bi.manager.client.EventAnalysisToolManager;
import com.loongtech.bi.manager.client.EventAnalysisToolManager.EventAnalysisData;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.bi.support.chart.ChartTool;
import com.loongtech.bi.support.chart.ChartType;
import com.loongtech.bi.support.chart.ChartUIData;
import com.loongtech.core.util.Time;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 客户端分析 —事件分析Action
 * @author Marin
 * @date 2015年09月17日
 */
@Controller
@Scope("session")
@RequestMapping("/client/iterativeEventClient")
public class IterativeEventClientBiAction extends BaseBiSearchAction {
	private static final long serialVersionUID = 1L;
	private Map<String, String> enterItmes = GameParamConfigManager.getItems(CommonGameParam.EVENT_ENTER_STEPCODE); // 进入步骤
	private Map<String, String> newUserEnterItemsRevise = GameParamConfigManager.getItemsRevise2(CommonGameParam.EVENT_NEWUSER_STEPCODE); // 新用户进入步骤
	private Map<String, String> allEnterItemsRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.EVENT_ALLUSER_STEPCODE); // 全部用户进入步骤

	private int enterId = CommonGameParam.EVENT_NEWUSER_STEPCODE.COMMONID; //进入步骤类型
	private String dateRadio = "1";
	private List<EventAnalysisData> dataList1;  // 前端要显示的数据1
    private List<EventAnalysisToolManager.EventAnalysisDataByPhone> dataListByPhone;  // 分机型数据
	private ChartUIData chartData1;  // 前端要显示的柱状图1数据
	private ChartUIData chartData2;  // 前端要显示的柱状图1数据

    private List<EventAnalysisToolManager.EventAnalysisDataChannel> dataListChannel;  // 渠道通过率数据
    private ChartUIData chartDataChannel;  // 渠道通过率图表

    private EventAnalysisToolManager.EventAnalysisDataChannel selectedData;

	@Autowired
	private EventAnalysisToolManager eventAnalysisToolManager;

    @RequestMapping(value = "initParam.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("res", "0");
            result.put("channelItmes", channelItmes);
            result.put("platformItmes", platformItmes);
            enterItmes.remove("全部");
            result.put("enterItmes", enterItmes);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

	/**
	 * 切换天数
	 */
	public void radioChange() {
		search();
	}
	
	//获得商城名称
	public String getStepCodeName(Object itemType) {
		String key = itemType == null ? "" : Math.abs(Integer.parseInt(itemType.toString())) + "";
		return (allEnterItemsRevise.get(key) == null) ? key : allEnterItemsRevise.get(key); 
	}

    @RequestMapping(value = "search.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String dstart, @RequestParam String dend, String platform, String channel, @RequestParam String enterId, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            dateStart = Time.formatDate(dstart, Time.TIMEPATTERN_SIMPLE);
            dateEnd = Time.formatDate(dend, Time.TIMEPATTERN_SIMPLE);
            this.enterId = Integer.parseInt(enterId);

            chartData1 = null;
            chartData2 = null;
            chartDataChannel = null;

            dataList1 = eventAnalysisToolManager.getAllData(dateStart, dateEnd, platform, channel, queryServer,newUserEnterItemsRevise,allEnterItemsRevise, this.enterId);
            if (dataList1 != null && dataList1.size() > 0) {
                List<EventAnalysisToolManager.EventAnalysisData1> list1 = new ArrayList<>();
                List<EventAnalysisToolManager.EventAnalysisData2> list2 = new ArrayList<>();

                for(EventAnalysisData data : dataList1) {
                    EventAnalysisToolManager.EventAnalysisData1 data1 = eventAnalysisToolManager.new EventAnalysisData1();
                    try {
                        BeanUtils.copyProperties(data1, data);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    //设置名称
                    data1.setStepcodeName(getStepCodeName(data1.getStepcode()));
                    list1.add(data1);

                    EventAnalysisToolManager.EventAnalysisData2 data2 = eventAnalysisToolManager.new EventAnalysisData2();
                    try {
                        BeanUtils.copyProperties(data2, data);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    //设置名称
                    data2.setStepcodeName(getStepCodeName(data2.getStepcode()));
                    list2.add(data2);
                }

                Collections.reverse(list1);
                Collections.reverse(list2);

                //构造柱形图
                chartData1 = new ChartUIData();
                chartData1.setJsonType(ChartType.COLUMN.type);
                chartData1.setJsonStr(new ChartTool(list1, EventAnalysisToolManager.EventAnalysisData1.class, "").loadData(chartData1.getJsonType()));
                chartData1.setAllItmes(ChartTool.getAllItems(EventAnalysisToolManager.EventAnalysisData1.class));

                //构造折线图
                chartData2 = new ChartUIData();
                chartData2.setJsonType(ChartType.SPLINE.type);
                chartData2.setJsonStr(new ChartTool(list2, EventAnalysisToolManager.EventAnalysisData2.class, "").loadData(chartData2.getJsonType()));
                chartData2.setAllItmes(ChartTool.getAllItems(EventAnalysisToolManager.EventAnalysisData2.class));
            }

            dataListChannel = eventAnalysisToolManager.getAllChannelData(dateStart, dateEnd, queryPlatform, queryChannel, queryServer, newUserEnterItemsRevise, allEnterItemsRevise, this.enterId);
            if (dataListChannel != null && dataListChannel.size() > 0) {
                //构造柱形图
                chartDataChannel = new ChartUIData();
                chartDataChannel.setJsonType(ChartType.COLUMN.type);
                chartDataChannel.setJsonStr(new ChartTool(dataListChannel.size() > 20 ? dataListChannel.subList(0, 20) : dataListChannel, EventAnalysisToolManager.EventAnalysisDataChannel.class, "").loadData(chartDataChannel.getJsonType(), true));
                chartDataChannel.setAllItmes(ChartTool.getAllItems(EventAnalysisToolManager.EventAnalysisDataChannel.class));
            }

            result.put("res", "0");
            result.put("dataList1", dataList1);
            result.put("chartData1", chartData1);
            result.put("chartData2", chartData2);
            result.put("dataListChannel", dataListChannel);
            result.put("chartDataChannel", chartDataChannel);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @RequestMapping(value = "searchbyphone.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void searchByPhone(HttpServletRequest request, HttpServletResponse response, @RequestParam String dstart, @RequestParam String dend, String platform, String channel, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            dataListByPhone = eventAnalysisToolManager.getAllDataByPhone(Time.formatDate(dstart,"yyyy-MM-dd"), Time.formatDate(dend,"yyyy-MM-dd"), platform, channel, queryServer,newUserEnterItemsRevise);

            List<ArrayList<String>> totalAchieve = new ArrayList<>();
            List<ArrayList<String>> lostRate = new ArrayList<>();
            for (int i = 0; i < dataListByPhone.size(); i++) {
                ArrayList<String> temp = new ArrayList<>();
                ArrayList<String> temp2 = new ArrayList<>();
                temp.add(dataListByPhone.get(i).getBeginnum().toString());
                temp.add(dataListByPhone.get(i).getDevieModel());
                temp2.add(dataListByPhone.get(i).getBeginnum().toString());
                temp2.add(dataListByPhone.get(i).getDevieModel());
                for (int j = 0; j < dataListByPhone.get(i).getSteps().size(); j++) {
                    if (dataListByPhone.get(i).getSteps().get(j) == null) {
                        temp.add("-");
                        temp2.add("-");
                    } else {
                        temp.add(dataListByPhone.get(i).getSteps().get(j).getTotalAchieve().toString());
                        temp2.add(dataListByPhone.get(i).getSteps().get(j).getLostRate().toString());
                    }
                }
                totalAchieve.add(temp);
                lostRate.add(temp2);
            }
            result.put("res", "0");

            result.put("newUserEnterItemsRevise", newUserEnterItemsRevise);
            result.put("totalAchieve", totalAchieve);
            result.put("lostRate", lostRate);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    @RequestMapping(value = "updateChannel.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void updateChannel(HttpServletRequest request, HttpServletResponse response, String channel, String callback) {
        try {
            queryChannel = channel;
            updateServerItmes();
            Map<String, Object> result = new HashMap<>();
            result.put("res", "0");
            result.put("platformItmes", platformItmes);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @RequestMapping(value = "updatePlatform.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void updatePlatform(HttpServletRequest request, HttpServletResponse response, String platform, String callback) {
        try {
            queryPlatform = platform;
            updateChannelItmes();
            Map<String, Object> result = new HashMap<>();
            result.put("res", "0");
            result.put("channelItmes", channelItmes);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @Override
    public void search() {

    }

    @Override
	protected String csvContent() {
		return "事件分析";
	}

	@Override
    protected String csvFileName() {
	    return "事件分析";
    }

	public List<EventAnalysisData> getDataList1() {
		return dataList1;
	}

	public void setDataList1(List<EventAnalysisData> dataList1) {
		this.dataList1 = dataList1;
	}

	public ChartUIData getChartData1() {
		return chartData1;
	}

	public void setChartData1(ChartUIData chartData1) {
		this.chartData1 = chartData1;
	}

	public String getDateRadio() {
		return dateRadio;
	}

	public void setDateRadio(String dateRadio) {
		this.dateRadio = dateRadio;
	}

	public int getEnterId() {
		return enterId;
	}

	public void setEnterId(int enterId) {
		this.enterId = enterId;
	}

	public Map<String, String> getEnterItmes() {
		return enterItmes;
	}

	public void setEnterItmes(Map<String, String> enterItmes) {
		this.enterItmes = enterItmes;
	}

	public ChartUIData getChartData2() {
		return chartData2;
	}

	public void setChartData2(ChartUIData chartData2) {
		this.chartData2 = chartData2;
	}

    public List<EventAnalysisToolManager.EventAnalysisDataChannel> getDataListChannel() {
        return dataListChannel;
    }

    public void setDataListChannel(List<EventAnalysisToolManager.EventAnalysisDataChannel> dataListChannel) {
        this.dataListChannel = dataListChannel;
    }

    public ChartUIData getChartDataChannel() {
        return chartDataChannel;
    }

    public void setChartDataChannel(ChartUIData chartDataChannel) {
        this.chartDataChannel = chartDataChannel;
    }

    public EventAnalysisToolManager.EventAnalysisDataChannel getSelectedData() {
        return selectedData;
    }

    public void setSelectedData(EventAnalysisToolManager.EventAnalysisDataChannel selectedData) {
        this.selectedData = selectedData;
    }

    public List<EventAnalysisToolManager.EventAnalysisDataByPhone> getDataListByPhone() {
        return dataListByPhone;
    }

    public void setDataListByPhone(List<EventAnalysisToolManager.EventAnalysisDataByPhone> dataListByPhone) {
        this.dataListByPhone = dataListByPhone;
    }
}
